package com.nehc.nettyserver.controller;

import com.nehc.nettyserver.common.model.Message;
import com.nehc.nettyserver.service.MessageService;
import com.nehc.nettyserver.netty.ChannelManager;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息控制器
 * 提供消息相关API
 * 
 * @author NEHC
 */
@RestController
@RequestMapping("/messages")
@RequiredArgsConstructor
public class MessageController {
    
    private final MessageService messageService;
    private final ChannelManager channelManager;
    
    /**
     * 获取消息
     */
    @GetMapping("/{messageId}")
    public ResponseEntity<Message> getMessage(@PathVariable String messageId) {
        Message message = messageService.getMessage(messageId);
        if (message != null) {
            return ResponseEntity.ok(message);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取用户消息
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Message>> getUserMessages(
            @PathVariable String userId,
            @RequestParam(defaultValue = "20") int limit) {
        
        List<Message> messages = messageService.getUserMessages(userId, limit);
        return ResponseEntity.ok(messages);
    }
    
    /**
     * 发送消息给用户
     */
    @PostMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> sendMessageToUser(
            @PathVariable String userId,
            @RequestBody Message message) {
        
        Map<String, Object> result = new HashMap<>();
        
        if (message == null || message.getPayload() == null || !message.getPayload().containsKey("content")) {
            result.put("success", false);
            result.put("message", "消息内容不能为空");
            return ResponseEntity.badRequest().body(result);
        }
        
        // 包装成系统消息
        Message systemMessage = Message.createSystemMessage(message.getPayload().get("content").toString());
        if (message.getPayload().containsKey("title")) {
            systemMessage.addPayload("title", message.getPayload().get("title"));
        }
        
        // 生成JSON字符串
        String messageJson = toJson(systemMessage);
        
        // 发送消息
        int count = channelManager.sendToUser(userId, messageJson);
        
        result.put("success", count > 0);
        result.put("message", count > 0 ? "消息发送成功" : "消息发送失败，用户可能不在线");
        result.put("recipientCount", count);
        result.put("messageId", systemMessage.getId());
        
        // 保存消息
        messageService.saveMessage(systemMessage);
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取消息统计
     */
    @GetMapping("/stats")
    public ResponseEntity<MessageService.MessageStats> getMessageStats(
            @RequestParam(defaultValue = "0") long startTime,
            @RequestParam(defaultValue = "0") long endTime) {
        
        if (startTime == 0) {
            startTime = System.currentTimeMillis() - 24 * 60 * 60 * 1000; // 默认24小时前
        }
        
        if (endTime == 0) {
            endTime = System.currentTimeMillis();
        }
        
        MessageService.MessageStats stats = messageService.getMessageStats(startTime, endTime);
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 将对象转换为JSON字符串
     */
    private String toJson(Object obj) {
        try {
            return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(obj);
        } catch (Exception e) {
            return "{}";
        }
    }
} 